from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import TemplateView, DetailView
from django.contrib.auth.models import User
from django.db.models import Count, Sum
from django.http import HttpResponseRedirect

from .models import SiteInfo, Advertisement, PageVisitCount
from rules.models import CursorRule, Tag
from rules.views import RuleListView

class HomeView(RuleListView):
    """首页视图"""
    template_name = 'core/home.html'
    paginate_by = None  # 不分页显示
    
    def get_queryset(self):
        # 获取最新规则
        return CursorRule.objects.filter(
            status='approved'
        ).select_related('author').prefetch_related('tags').order_by('-created_at')[:12]

class AboutView(TemplateView):
    """关于页面视图"""
    template_name = 'core/about.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['site_info'] = SiteInfo.get_site_info()
        return context

def ad_click_view(request, pk):
    """广告点击处理视图"""
    ad = get_object_or_404(Advertisement, pk=pk, is_active=True)
    
    # 增加点击计数
    ad.increment_click()
    
    # 跳转到广告链接
    return HttpResponseRedirect(ad.url)
